package com.yangcangclub.commons.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 汉字转拼音
 */
public class PinYinUtil {


    /**
     *
     * 将汉字转换成拼音
     *
     * @param hanzi
     *
     * @param separator
     *
     * @return
     */
    @SuppressWarnings("deprecation")
    public static String hanziToPinyin(String hanzi, String separator) {

        // 创建汉语拼音处理类

        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();

        // 输出设置，大小写，音标方式

        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);

        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

        String pinyingStr = "";

        try {

            pinyingStr = PinyinHelper.toHanyuPinyinString(hanzi, defaultFormat,
                    separator);

        } catch (BadHanyuPinyinOutputFormatCombination e) {

            e.printStackTrace();

        }

        return pinyingStr;

    }

    /**
     * 过滤非法字符
     * @param arg
     * @return
     */
    public static String filterIllegalString(String arg) {
        if(StringUtil.isFullEmpty(arg)) {
            return "";
        }
        char illegal[] = { '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*',
                '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@',
                '\\', '^', '_', '`', '{', '|', '[', ']', '}', '~', '\u3002',
                '\uFF0C', '\u3001', '\uFF1B', '\uFF1A', '\uFF1F', '\uFF01',
                '\u2018', '\u2019', '\u201C', '\u201D', '\u3014', '\u3015',
                '\u3008', '\u3009', '\u300A', '\u300B' };
        arg = arg.replaceAll(" ", "");
        char inch[] = arg.toCharArray();
        for (int j = 0, m = inch.length; j < m; j++) {
            for (int i = 0, n = illegal.length; i < n; i++) {
                if (inch[j] == illegal[i]) {
                    inch[j] = '&';
                }
            }
        }
        arg = new String(inch);
        arg = arg.replaceAll("&", "");
        return arg;
    }
    
    
    
}
